<template>
  <div class="real-name-auth-container">
    <div class="auth-header">
      <h2>实名认证</h2>
      <p class="subtitle" v-if="frontResult || backResult">已认证，可以重新上传更新信息</p>
      <p class="subtitle" v-else>请上传身份证正反面图片完成实名认证</p>
    </div>

    <div class="auth-content">
      <!-- 身份证正面 -->
      <div class="id-card-section">
        <h3>身份证正面</h3>
        <div class="upload-area" :class="{ 'has-image': frontImage }">
          <input
            type="file"
            ref="frontInput"
            accept="image/*"
            @change="handleFrontImageUpload"
            style="display: none"
          />
          <div v-if="!frontImage" class="upload-placeholder" @click="triggerFrontUpload">
            <div class="upload-icon">📷</div>
            <p>点击上传身份证正面</p>
          </div>
          <div v-else class="image-preview">
            <img :src="frontImage" alt="身份证正面" />
            <button class="remove-btn" @click="removeFrontImage">✕</button>
          </div>
        </div>
        <div v-if="frontResult" class="result-display">
          <h4>{{ frontImage ? '识别结果：' : '当前认证信息：' }}</h4>
          <div class="result-item">
            <span class="label">姓名：</span>
            <span class="value">{{ frontResult.name }}</span>
          </div>
          <div class="result-item">
            <span class="label">身份证号：</span>
            <span class="value">{{ maskIdCard(frontResult.id_card_num) }}</span>
          </div>
          <div class="result-item">
            <span class="label">性别：</span>
            <span class="value">{{ frontResult.gender }}</span>
          </div>
          <div class="result-item">
            <span class="label">民族：</span>
            <span class="value">{{ frontResult.nation }}</span>
          </div>
          <div class="result-item">
            <span class="label">出生日期：</span>
            <span class="value">{{ frontResult.birth }}</span>
          </div>
          <div class="result-item">
            <span class="label">住址：</span>
            <span class="value">{{ frontResult.address }}</span>
          </div>
        </div>
      </div>

      <!-- 身份证反面 -->
      <div class="id-card-section">
        <h3>身份证反面</h3>
        <div class="upload-area" :class="{ 'has-image': backImage }">
          <input
            type="file"
            ref="backInput"
            accept="image/*"
            @change="handleBackImageUpload"
            style="display: none"
          />
          <div v-if="!backImage" class="upload-placeholder" @click="triggerBackUpload">
            <div class="upload-icon">📷</div>
            <p>点击上传身份证反面</p>
          </div>
          <div v-else class="image-preview">
            <img :src="backImage" alt="身份证反面" />
            <button class="remove-btn" @click="removeBackImage">✕</button>
          </div>
        </div>
        <div v-if="backResult" class="result-display">
          <h4>{{ backImage ? '识别结果：' : '当前认证信息：' }}</h4>
          <div class="result-item">
            <span class="label">签发机关：</span>
            <span class="value">{{ backResult.issuing_authority }}</span>
          </div>
          <div class="result-item">
            <span class="label">有效期限：</span>
            <span class="value">{{ backResult.valid_date }}</span>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-section">
        <button 
          class="submit-btn" 
          :disabled="isProcessing"
          @click="handleSubmit"
        >
          {{ isProcessing ? '处理中...' : (frontResult ? (frontImage || backImage ? '更新认证信息' : '返回') : '提交认证') }}
        </button>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        {{ error }}
      </div>

      <!-- 成功提示 -->
      <div v-if="success" class="success-message">
        {{ success }}
      </div>
    </div>

    <!-- 底部导航栏 -->
    <BottomNavigation />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import BottomNavigation from '../components/BottomNavigation.vue'

const router = useRouter()
const frontInput = ref(null)
const backInput = ref(null)
const frontImage = ref('')
const backImage = ref('')
const frontResult = ref(null)
const backResult = ref(null)
const isProcessing = ref(false)
const error = ref('')
const success = ref('')
const userId = ref(null)

// 获取用户ID和已有认证信息
onMounted(async () => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    router.push('/login')
    return
  }

  try {
    // 获取用户ID
    const userResponse = await fetch('http://localhost:8000/api/user/info', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (userResponse.ok) {
      const userData = await userResponse.json()
      userId.value = userData.id
    } else {
      router.push('/login')
      return
    }

    // 获取已有认证信息
    try {
      const authResponse = await fetch('http://localhost:8000/api/real-name-auth/info', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (authResponse.ok) {
        const authData = await authResponse.json()
        if (authData.success && authData.auth_info) {
          // 如果有已有信息，显示在页面上
          if (authData.auth_info.real_name) {
            frontResult.value = {
              name: authData.auth_info.real_name,
              id_card_num: authData.auth_info.id_card_num,
              gender: authData.auth_info.gender || '',
              nation: authData.auth_info.nation || '',
              birth: authData.auth_info.birth || '',
              address: authData.auth_info.address || ''
            }
          }
          if (authData.auth_info.issuing_authority) {
            backResult.value = {
              issuing_authority: authData.auth_info.issuing_authority || '',
              valid_date: authData.auth_info.valid_date || ''
            }
          }
        }
      }
    } catch (authErr) {
      console.error('获取认证信息失败:', authErr)
      // 不影响页面加载，只是无法显示已有信息
    }
  } catch (err) {
    console.error('获取信息失败:', err)
    router.push('/login')
  }
})

// 将图片转换为Base64（包含data:image前缀，后端会自动处理）
const imageToBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      // reader.result 格式为 "data:image/png;base64,..." 或 "data:image/jpeg;base64,..."
      // 后端OCR工具会自动处理，去掉前缀
      resolve(reader.result)
    }
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

// 触发正面图片上传
const triggerFrontUpload = () => {
  frontInput.value?.click()
}

// 处理正面图片上传
const handleFrontImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    error.value = '请选择图片文件'
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    error.value = '图片大小不能超过5MB'
    return
  }

  try {
    isProcessing.value = true
    error.value = ''
    success.value = ''

    // 显示预览
    const base64 = await imageToBase64(file)
    frontImage.value = base64

    // 调用OCR接口
    const token = localStorage.getItem('access_token')
    const response = await fetch('http://localhost:8000/api/real-name-auth/ocr/idcard', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        image_base64: base64,
        card_side: 'front',
        user_id: userId.value
      })
    })

    // 处理响应
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ detail: '请求失败' }))
      throw new Error(errorData.detail || errorData.message || '识别失败')
    }

    const data = await response.json()

    if (data.success) {
      frontResult.value = data.data
      success.value = data.message || '身份证正面识别成功！'
      // 清除错误信息
      error.value = ''
    } else {
      error.value = data.message || '识别失败，请重试'
      frontImage.value = ''
    }
  } catch (err) {
    console.error('识别失败:', err)
    error.value = err.message || '识别失败，请检查网络连接'
    frontImage.value = ''
    frontResult.value = null
  } finally {
    isProcessing.value = false
  }
}

// 移除正面图片
const removeFrontImage = () => {
  frontImage.value = ''
  frontResult.value = null
  if (frontInput.value) {
    frontInput.value.value = ''
  }
}

// 触发反面图片上传
const triggerBackUpload = () => {
  backInput.value?.click()
}

// 处理反面图片上传
const handleBackImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    error.value = '请选择图片文件'
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    error.value = '图片大小不能超过5MB'
    return
  }

  try {
    isProcessing.value = true
    error.value = ''
    success.value = ''

    // 显示预览
    const base64 = await imageToBase64(file)
    backImage.value = base64

    // 调用OCR接口
    const token = localStorage.getItem('access_token')
    const response = await fetch('http://localhost:8000/api/real-name-auth/ocr/idcard', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        image_base64: base64,
        card_side: 'back',
        user_id: userId.value
      })
    })

    // 处理响应
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ detail: '请求失败' }))
      throw new Error(errorData.detail || errorData.message || '识别失败')
    }

    const data = await response.json()

    if (data.success) {
      backResult.value = data.data
      success.value = data.message || '身份证反面识别成功！'
      // 清除错误信息
      error.value = ''
    } else {
      error.value = data.message || '识别失败，请重试'
      backImage.value = ''
    }
  } catch (err) {
    console.error('识别失败:', err)
    error.value = err.message || '识别失败，请检查网络连接'
    backImage.value = ''
    backResult.value = null
  } finally {
    isProcessing.value = false
  }
}

// 移除反面图片
const removeBackImage = () => {
  backImage.value = ''
  backResult.value = null
  if (backInput.value) {
    backInput.value.value = ''
  }
}

// 提交认证
const handleSubmit = () => {
  if (!frontResult) {
    error.value = '请先上传身份证正面'
    return
  }

  if (frontImage || backImage) {
    // 如果有新上传的图片，说明已经识别并保存了
    success.value = '实名认证信息已更新！'
    // 2秒后返回个人信息页面
    setTimeout(() => {
      router.push('/profile')
    }, 2000)
  } else {
    // 如果没有新上传的图片，只是查看已有信息，直接返回
    router.push('/profile')
  }
}

// 隐藏身份证号中间部分
const maskIdCard = (idCard) => {
  if (!idCard) return ''
  if (idCard.length < 10) return idCard
  return idCard.substring(0, 6) + '********' + idCard.substring(idCard.length - 4)
}
</script>

<style scoped>
.real-name-auth-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  padding: 24px 24px 80px 24px;
  background: #f8f8f8;
  overflow-y: auto;
  box-sizing: border-box;
}

.auth-header {
  text-align: center;
  margin-bottom: 32px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.auth-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.subtitle {
  margin: 0;
  color: #999;
  font-size: 14px;
}

.auth-content {
  max-width: 800px;
  margin: 0 auto;
}

.id-card-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.id-card-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.upload-area:hover {
  border-color: #ff2442;
  background: #fff5f5;
}

.upload-area.has-image {
  border: 2px solid #ff2442;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.upload-icon {
  font-size: 48px;
}

.upload-placeholder p {
  margin: 0;
  color: #999;
  font-size: 14px;
}

.image-preview {
  position: relative;
  display: inline-block;
  max-width: 100%;
}

.image-preview img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
  display: block;
}

.remove-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #ff2442;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.result-display {
  margin-top: 20px;
  padding: 16px;
  background: #f8f8f8;
  border-radius: 8px;
}

.result-display h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.result-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.result-item .label {
  color: #999;
  min-width: 100px;
}

.result-item .value {
  color: #333;
  font-weight: 500;
}

.submit-section {
  text-align: center;
  margin-top: 32px;
}

.submit-btn {
  padding: 14px 48px;
  background: #ff2442;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  background: #e01d37;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.error-message {
  margin-top: 20px;
  padding: 12px;
  background: #fee;
  color: #c33;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
}

.success-message {
  margin-top: 20px;
  padding: 12px;
  background: #efe;
  color: #3c3;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .real-name-auth-container {
    padding: 16px;
  }

  .id-card-section {
    padding: 20px;
  }

  .upload-area {
    padding: 30px 20px;
  }
}
</style>

